package net.esj.alipay.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.esj.alipay.util.AlipayNotify;
import net.melon.order.inst.service.OrderService;
import net.melon.order.pojo.Order;
import net.melon.order.pojo.Order.OrderState;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class AlipayReturnServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 5778436221047048453L;
	
	private OrderService orderService;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		resp.setContentType("text/html;charset=UTF-8");
		
		ServletContext servletContext = this.getServletContext();
		
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		
		orderService = (OrderService) context.getBean("orderService");
		
		PrintWriter out = resp.getWriter();
		try {
			Map<String,String> params = new HashMap<String,String>();
			Map requestParams = req.getParameterMap();
			for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String[] values = (String[]) requestParams.get(name);
				String valueStr = "";
				for (int i = 0; i < values.length; i++) {
					valueStr = (i == values.length - 1) ? valueStr + values[i]
							: valueStr + values[i] + ",";
				}
				//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
				params.put(name, valueStr);
			}
			
			//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
			//商户订单号

			String out_trade_no = new String(req.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

			//支付宝交易号
			//String trade_no = new String(req.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

			//交易状态
			String trade_status = new String(req.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

			//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
			
			//计算得出通知验证结果
			boolean verify_result = AlipayNotify.verify(params);
			
			if(verify_result){//验证成功
				//////////////////////////////////////////////////////////////////////////////////////////
				//请在这里加上商户的业务逻辑程序代码

				//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
				if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
					//判断该笔订单是否在商户网站中已经做过处理
						//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
						//如果有做过处理，不执行商户的业务程序
					//req.setAttribute("return_url",return_url);
					Order order = orderService.getOrderById(out_trade_no);
					if(order!=null && order.getState()==OrderState.NO_PAY.getState()){
						orderService.updatePayOrder(order);
					}
					String return_url = "/paySuccess.htm";
    		   		RequestDispatcher dispatcher = req.getRequestDispatcher(return_url);    // 使用req对象获取RequestDispatcher对象
    	            dispatcher.forward(req, resp);
				}else{
					String return_url = "/payFail.htm";
    		   		RequestDispatcher dispatcher = req.getRequestDispatcher(return_url);    // 使用req对象获取RequestDispatcher对象
    	            dispatcher.forward(req, resp);
				}
				//该页面可做页面美工编辑
				//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

				//////////////////////////////////////////////////////////////////////////////////////////
			}else{
				//该页面可做页面美工编辑
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

}
